package com.example.zyghfeedback;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FeedbackDetails extends AppCompatActivity {
    private View include;
    private ImageView iv_back, iv_photo;
    private RecyclerView recycler_view;
    private TextView tv_send;
    private EditText et_input;
    private MyDetailsAdapter myDetailsAdapter;
    //反馈信息序列号
    private String serialNumber;
    //信息工具类
    private List<MyFeedbackDetailsModel> myFeedbackDetailsModel = new ArrayList<>();
    //上一页传递数据
    long feedbackTime;
    String content;
    //线程传递数据
    private Message send_message;
    //页码
    private int pageNum = 1;
    //每页条数
    private int pageSize = 10;
    String path;
    private String ZyKey = "1d3b1b3f67b148b59cdc73e4d2635463";

    //判断是否是第一次进入
    private static boolean isFirstEnter = true;
    public static final int CHOOSE_PHOTO = 2;// 相册
    //下拉刷新
    private RefreshLayout srl_layout;
    //获取图片
    private File headFile = null;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 101){
//                srl_layout.autoRefresh();
                recycler_view.scrollToPosition(myDetailsAdapter.getItemCount() - 1);
                myDetailsAdapter.notifyDataSetChanged();
            }else {
                recycler_view.scrollToPosition(myDetailsAdapter.getItemCount() - 1);
                myDetailsAdapter.notifyDataSetChanged();
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.feedback_details);
        setInit();
        setOnclick();
    }

    private void setInit() {
        Intent intent = getIntent();
        serialNumber = intent.getStringExtra("serialNumber");
        feedbackTime = intent.getLongExtra("feedbackTime", 0);
        content = intent.getStringExtra("content");
        srl_layout = findViewById(R.id.srl_layout);
        getdata();
        include = findViewById(R.id.include);
        iv_back = include.findViewById(R.id.iv_back);
        tv_send = findViewById(R.id.tv_send);
        iv_photo = findViewById(R.id.iv_photo);
        et_input = findViewById(R.id.et_input);
        recycler_view = findViewById(R.id.recycler_view);
        //设置布局管理器
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recycler_view.setLayoutManager(mLayoutManager);
        myFeedbackDetailsModel.add(new MyFeedbackDetailsModel(content, "0", "0", "3", feedbackTime));
    }

    private void setOnclick() {
        //设置adapter
        myDetailsAdapter = new MyDetailsAdapter(myFeedbackDetailsModel, this);
        recycler_view.setAdapter(myDetailsAdapter);
        recycler_view.scrollToPosition(myDetailsAdapter.getItemCount() - 1);//此句为设置显示
        //设置Item添加和移除的动画
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        srl_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum++;
                getdata();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取用户输入
                String text = et_input.getText().toString();
                //用户输入发送到网络上
                if (!headFile.exists() || headFile.length() == 0) {
                    setsend(text, null);
                } else {
                    setsend("", headFile);
                    FileWriter fileWriter = null;
                    try {
                        fileWriter = new FileWriter(headFile);
                        fileWriter.write("");
                        fileWriter.flush();
                        fileWriter.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //内容发送成功之后清空输入文本框
                et_input.setText("");
            }
        });
        iv_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show();
            }
        });
    }

    private void show() {
        final Dialog dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_item, null);
        //相册
        Button bt_camera = inflate.findViewById(R.id.bt_camera);
        //取消
        Button bt_cancel = inflate.findViewById(R.id.bt_cancel);
        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;
        dialogWindow.setAttributes(lp);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                if (ContextCompat.checkSelfPermission(FeedbackDetails.this,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(FeedbackDetails.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    openAlbum();
                }
            }
        });
        dialog.show();
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);//打开相册
    }

    //相册
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "你拒绝了权限申请，可能无法打开相册哟", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    // 判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.
                    getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }

        displayImage(imagePath); // 根据图片路径显示图片

    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);

    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.
                        Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            headFile = saveMyBitmap(bitmap, "head");
            setsend("", headFile);
        } else {
            Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
        }
    }

    //将bitmap转化为png格式
    public File saveMyBitmap(Bitmap mBitmap, String prefix) {
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File file = null;
        try {
            file = File.createTempFile(
                    prefix,  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
            FileOutputStream fos = new FileOutputStream(file);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 10, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    private void setsend(final String text, final File bitmap) {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                    JSONObject json = new JSONObject();
                    try {
                        //反馈信息序列号
                        json.put("serialNumber", serialNumber);
                        //消息内容
                        if (text.isEmpty()) {
                            json.put("message", upphoto(bitmap));
                            //消息类型(0:文本；1:图片；2：系统)
                            json.put("type", "1");
                        } else {
                            json.put("message", text);
                            //消息类型(0:文本；1:图片；2：系统)
                            json.put("type", "0");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //1 . 拿到OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
                    RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
                    //3 . 构建Request,将FormBody作为Post方法的参数传入
                    Request request = new Request.Builder()
                            .url("http://172.28.60.97:8200/ZYGameServer_v2/app/v2/sendMessage")
                            .post(requestBody)
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    getfeedback(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //一个JSON对象——JSONObject{}
            //一个JSON数组——JSONArray[]
            private void getfeedback(String responseData) {
                try {
                    JSONObject jsonObject1 = new JSONObject(responseData);
                    String code = jsonObject1.getString("code");
                    if (code.equals("0")) {
                        pageNum = 1;
                        myFeedbackDetailsModel.clear();
                        myFeedbackDetailsModel.add(new MyFeedbackDetailsModel(content, "0", "0", "3", feedbackTime));
                        getdata();
                        if (text.isEmpty()){
                            send_message = Message.obtain();
                            send_message.what = 101;
                            handler.sendMessage(send_message);
                        }else {
                            send_message = Message.obtain();
                            send_message.what = 100;
                            handler.sendMessage(send_message);
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private String upphoto(final File bitmap) {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //1 . 拿到OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    // MediaType.parse() 里面是上传的文件类型。
                    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                    if (bitmap != null) {
                        RequestBody body = RequestBody.create(MediaType.parse("image/*"), bitmap);
                        // 参数分别为， 请求key ，文件名称 ， RequestBody
                        builder.addFormDataPart("zyFile", bitmap.getName(), body);
                    }
                    MultipartBody requestBody = builder.build();
//                    3 . 构建Request,将FormBody作为Post方法的参数传入
                    Request request = new Request.Builder()
                            .url("http://172.28.60.97:8200/ZYGameServer_v2/v1/upload/feedback")
                            .post(requestBody)
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    getfeedback(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //一个JSON对象——JSONObject{}
            //一个JSON数组——JSONArray[]
            private void getfeedback(String responseData) {
                try {
                    JSONObject jsonObject1 = new JSONObject(responseData);
                    path = jsonObject1.getString("path");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return path;
    }

    private void getdata() {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                    JSONObject json = new JSONObject();
                    try {
                        json.put("serialNumber", serialNumber);
                        json.put("pageNum", pageNum);
                        json.put("pageSize", pageSize);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //1 . 拿到OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
                    RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
                    //3 . 构建Request,将FormBody作为Post方法的参数传入
                    Request request = new Request.Builder()
                            .url("http://172.28.60.97:8200/ZYGameServer_v2/app/v2/getChatInfoByPage")
                            .post(requestBody)
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    getfeedback(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //一个JSON对象——JSONObject{}
            //一个JSON数组——JSONArray[]
            private void getfeedback(String responseData) {
                try {
                    JSONObject jsonObject1 = new JSONObject(responseData);
                    JSONArray jsonArray = jsonObject1.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        //消息内容
                        String message = jsonObject.getString("message");
                        //消息类型(0:文本；1:图片；；2：系统)
                        String type = jsonObject.getString("type");
                        //0:未读；1:已读
                        String read = jsonObject.getString("read");
                        //消息来源(0:用户；1:平台)
                        String source = jsonObject.getString("source");
                        // 创建时间
                        long createTime = jsonObject.getLong("createTime");

                        myFeedbackDetailsModel.add(new MyFeedbackDetailsModel(message, type, read, source, createTime));
                    }
                    send_message = Message.obtain();
                    send_message.what = 100;
                    handler.sendMessage(send_message);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
